import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:screenshot/screenshot.dart';
import 'package:yysk_app/model/common_model/get_upload_key_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/login/forgot_password_page.dart';
import 'package:yysk_app/pages/login/login_controller.dart';
import 'package:yysk_app/pages/login/login_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/customer_service/customer_service_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_abount_us.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_controller.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_info.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/account_been_frozen_dialog.dart';
import 'package:yysk_app/utils/check_for_updates.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/suspend_account_dialog.dart';
import 'package:yysk_app/utils/upgrade_notice_dialog.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/input_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/list_route_tile.dart';
import 'package:image/image.dart' as img;
import 'package:oktoast/oktoast.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

final ImagePicker picker = ImagePicker();

settingDrawer(BuildContext context, GlobalController globalController) {
  final TextEditingController nickNameController = TextEditingController();
  final SettingController settingController = Get.put(SettingController());
  final Rx<Uint8List?> screenImg = Rx<Uint8List?>(null);
  ScreenshotController screenshotController = ScreenshotController();

  return Drawer(
    width: 270.px,
    child: Scaffold(
      body: Obx(() {
        return Container(
          width: 270.px,
          height: context.height,
          padding: EdgeInsets.fromLTRB(20.px, 88.px, 20.px, 20.px),
          decoration: BoxDecoration(color: Color.fromRGBO(31, 33, 38, 1)),
          child: SingleChildScrollView(
            // ignore: unnecessary_null_comparison
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // ignore: unnecessary_null_comparison
                globalController != null
                    ? _box(
                      context: context,
                      title: '基本信息',
                      widget: Column(
                        children: [
                          ListRouteTile(
                            title: '头像',
                            route: '',
                            trailing: SizedBox(
                              width: 32,
                              height: 32,
                              child: LazyImage(
                                imageUrl:
                                    '${globalController.user.value?.avatarImg}',
                                borderRadius: 100,
                              ),
                            ),
                            onTap: () {
                              showConfirmDialog(
                                context: context,
                                message: '允许元宇时空访问相机相册权限',
                                messages: ['为实现您图片的拍摄或上传'],
                                actions: [
                                  ActionModel(
                                    label: '取消',
                                    colorStart: AppColors.backgroundColorGreyF8,
                                    colorEnd: AppColors.backgroundColorGreyF8,
                                    fontColor: AppColors.fontColor,
                                  ),
                                  ActionModel(
                                    label: '授权',
                                    onPressed: _uploadImage,
                                  ),
                                ],
                              );
                            },
                          ),
                          ListRouteTile(
                            title: '昵称',
                            route: '',
                            trailing: RichText(
                              textAlign: TextAlign.center,
                              text: TextSpan(
                                text:
                                    '${globalController.user.value?.nickName ?? '--'} ',
                                style: TextStyle(
                                  fontSize: 13.px,
                                  fontWeight: FontWeight.normal,
                                  color: AppColors.fontColor,
                                ),
                                children: <InlineSpan>[
                                  TextSpan(text: ' '),
                                  WidgetSpan(
                                    alignment: PlaceholderAlignment.middle,
                                    child: Icon(
                                      Icons.arrow_forward_ios,
                                      color: AppColors.backgroundColorGrey,
                                      size: 13.px,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // trailing: Text(
                            //   '${globalController.user.value?.nickName ?? '--'} ',
                            //   style: TextStyle(
                            //     fontSize: 13.px,
                            //     fontWeight: FontWeight.normal,
                            //     color: AppColors.fontColor,
                            //   ),
                            // ),
                            onTap: () {
                              showConfirmDialog(
                                context: context,
                                children: [
                                  InputWidget(
                                    hint: '请输入昵称',
                                    controller: nickNameController,
                                    maxLength: 15,
                                    inputType: TextInputType.name,
                                    backgroundColor:
                                        AppColors.backgroundColorGreyF8,
                                    buttonRadio: 300,
                                  ),
                                  hiSpace(height: 18.px),
                                ],
                                actions: [
                                  ActionModel(
                                    label: '取消',
                                    colorStart: AppColors.backgroundColorGreyF8,
                                    colorEnd: AppColors.backgroundColorGreyF8,
                                    fontColor: AppColors.fontColor,
                                  ),
                                  ActionModel(
                                    label: '保存',
                                    onPressed: () {
                                      updateNickName(nickNameController.text);
                                      nickNameController.text = '';
                                    },
                                  ),
                                ],
                              );
                            },
                          ),
                          ListRouteTile(
                            title: '注册账号',
                            route: '',
                            trailing: Text(
                              // '${globalController.user.value?.userTel ?? '--'} ',
                              '${globalController.user.value!.userTel?.substring(0, 3) ?? ''}*****${globalController.user.value!.userTel?.substring(globalController.user.value!.userTel!.length - 3) ?? ''}',
                              style: TextStyle(
                                fontSize: 13.px,
                                fontWeight: FontWeight.normal,
                                color: AppColors.fontColor,
                              ),
                            ),
                          ),
                          ListRouteTile(
                            title: 'ID',
                            route: '',
                            trailing: Text(
                              '${globalController.user.value?.showId ?? '--'} ',
                              style: TextStyle(
                                fontSize: 13.px,
                                fontWeight: FontWeight.normal,
                                color: AppColors.fontColor,
                              ),
                            ),
                          ),
                          ListRouteTile(
                            title: '实名认证',
                            route: '',
                            trailing: RichText(
                              textAlign: TextAlign.center,
                              text: TextSpan(
                                text:
                                    (globalController.user.value?.isSm ?? false)
                                        ? '已实名'
                                        : '未实名',
                                style: TextStyle(
                                  fontSize: 13.px,
                                  fontWeight: FontWeight.normal,
                                  color: AppColors.fontColorRed,
                                ),
                                children: <InlineSpan>[
                                  TextSpan(text: ' '),
                                  WidgetSpan(
                                    alignment: PlaceholderAlignment.middle,
                                    child: Icon(
                                      Icons.arrow_forward_ios,
                                      color: AppColors.backgroundColorGrey,
                                      size: 13.px,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            onTap: () {
                              (globalController.user.value?.isSm ?? false)
                                  ? Get.toNamed(SettingRealNameInfo.path)
                                  : Get.toNamed(SettingRealNameAuthPage.path);
                            },
                          ),
                        ],
                      ),
                    )
                    : Container(),
                _box(
                  context: context,
                  title: '账号安全',
                  widget: Column(
                    children: [
                      ListRouteTile(
                        title: '登录密码',
                        route: '',
                        onTap: () {
                          // Get.toNamed(ModifyPassword.path);
                          Get.toNamed(ForgotPasswordPage.path);
                        },
                      ),
                      ListRouteTile(
                        title: '交易密码',
                        route: '',
                        onTap: () {
                          Get.toNamed(ChangeExchangePassword.path);
                        },
                      ),
                    ],
                  ),
                ),
                _box(
                  context: context,
                  title: '其他',
                  widget: Column(
                    children: [
                      ListRouteTile(
                        title: '官方社群',
                        route: '',
                        onTap: () {
                          Future.delayed(
                            const Duration(milliseconds: 1500),
                            () {
                              screenshotController.capture().then((img) {
                                screenImg.value = img!;
                              });
                            },
                          );
                          showConfirmDialog(
                            showBgColor: false,
                            context: context,
                            closeButton: true,
                            children: [
                              Screenshot(
                                controller: screenshotController,
                                child: LazyImage(
                                  width: 281.px,
                                  height: 315.px,
                                  borderRadius: 0,
                                  imageUrl:
                                      globalController
                                          .staticInfo
                                          .value!
                                          .officialCommunity ??
                                      '',
                                ),
                              ),
                            ],
                            actions: [
                              ActionModel(
                                label: '保存图片',
                                onPressed: () {
                                  saveScreenshot(imgBytes: screenImg.value);
                                },
                              ),
                            ],
                          );
                        },
                      ),
                      ListRouteTile(
                        title: '关于我们',
                        route: '',
                        onTap: () {
                          Get.toNamed(AbountUsVC.path);
                        },
                      ),
                      ListRouteTile(
                        title: '当前版本',
                        route: '',
                        onTap: () {
                          fetchVersionInfo().then((res) {
                            chech_updata(res: res, context: Get.context!).then((
                              res,
                            ) {
                              if (res) showToast('已经是最新版本');
                            });
                          });
                        },
                        trailing: RichText(
                          text: TextSpan(
                            text: 'v${globalController.version}',
                            style: TextStyle(
                              fontSize: 15.px,
                              fontWeight: FontWeight.normal,
                              color: AppColors.fontColor,
                            ),
                            children: <InlineSpan>[
                              TextSpan(text: ' '),
                              WidgetSpan(
                                alignment: PlaceholderAlignment.middle,
                                child: Icon(
                                  Icons.arrow_forward_ios,
                                  color: AppColors.backgroundColorGrey
                                      .withValues(alpha: 0.67),
                                  size: 14.px,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),

                      ListRouteTile(
                        title: '清除缓存',
                        route: '',
                        onTap: () {
                          showConfirmDialog(
                            context: context,
                            fontSize: 16,
                            message: '您确定要清除缓存吗',
                            actions: [
                              ActionModel(
                                label: '取消',
                                colorStart: AppColors.backgroundColorGreyF8,
                                colorEnd: AppColors.backgroundColorGreyF8,
                                fontColor: AppColors.fontColor,
                              ),
                              ActionModel(
                                label: '确定',
                                onPressed: clearAppCache,
                              ),
                            ],
                          );
                        },
                      ),
                      ListRouteTile(
                        title: '联系客服',
                        route: '',
                        onTap: () {
                          Get.toNamed(CustomerServicePage.path);
                        },
                      ),
                      ListRouteTile(
                        title: '注销账号',
                        route: '',
                        onTap: () {
                          settingController.canCancelAccount(context);
                        },
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 10.px),
                ButtonWidget(
                  width: 238.px,
                  height: 46.px,
                  fontSize: 15.px,
                  border: Border.all(
                    width: 1.px,
                    color: AppColors.fontColorRed,
                  ),
                  backgroundColor: AppColors.backgroundColorBlack,
                  fontColor: AppColors.fontColorRed,
                  bgColorStart: Color.fromRGBO(31, 33, 38, 1),
                  bgColorEnd: Color.fromRGBO(31, 33, 38, 1),
                  contentType: ContentType.text,
                  label: '退出',
                  onPressed: () {
                    showConfirmDialog(
                      context: context,
                      fontSize: 16,
                      message: '是否确认退出当前账号?',
                      actions: [
                        ActionModel(
                          label: '取消',
                          colorStart: AppColors.backgroundColorGreyF8,
                          colorEnd: AppColors.backgroundColorGreyF8,
                          fontColor: AppColors.fontColor,
                        ),
                        ActionModel(
                          label: '确定',
                          onPressed: () {
                            _logout();
                          },
                        ),
                      ],
                    );
                  },
                ),
                // SizedBox(height: 10.px),
                // ButtonWidget(
                //   width: 238.px,
                //   height: 46.px,
                //   fontSize: 15.px,
                //   backgroundColor: AppColors.backgroundColorBlack,
                //   fontColor: AppColors.fontColorRed,
                //   bgColorStart: Color.fromRGBO(31, 33, 38, 1),
                //   bgColorEnd: Color.fromRGBO(31, 33, 38, 1),
                //   contentType: ContentType.text,
                //   label: '注销账号',
                //   onPressed: () {
                //     settingController.canCancelAccount(context);
                //     // showToast('注销账号');
                //   },
                // ),
              ],
            ),
          ),
        );
      }),
    ),
  );
}

_box({
  required BuildContext context,
  String title = '标题',
  required Widget widget,
}) {
  return Container(
    width: context.width,
    padding: EdgeInsets.only(bottom: 5.px),
    margin: EdgeInsets.only(bottom: 20.px),
    decoration: BoxDecoration(
      border: Border(
        bottom: BorderSide(width: 1.px, color: AppColors.backgroundColorGreyF8),
      ),
    ),
    child: Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 12.px,
            color: AppColors.backgroundColorGrey,
          ),
        ),
        SizedBox(height: 20.px),
        widget,
      ],
    ),
  );
}

Future<void> saveScreenshot({Uint8List? imgBytes}) async {
  // showToast( '点击');
  try {
    // 请求权限
    final PermissionState permission =
        await PhotoManager.requestPermissionExtend();

    if (!permission.isAuth) {
      showToast('保存失败：需要相册访问权限');
      return;
    }
    if (imgBytes == null) {
      showToast('制图中,请稍后点击保存');
      return;
    }
    // 保存到相册
    final AssetEntity? asset = await PhotoManager.editor.saveImage(
      imgBytes,
      filename:
          'Flutter_Screenshot_${DateTime.now().millisecondsSinceEpoch}.png',
    );

    if (asset != null) {
      showToast('保存成功');
    } else {
      // throw Exception('保存失败: ${result['errorMessage']}');
    }
  } catch (e) {
    showToast('保存失败');
  }
}

void _uploadImage() async {
  try {
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);

    // 2. 获取腾讯云上传地址
    await _getUploadUrl('${image?.name}').then((res) {
      //  _uploadToTencentCloud(res, File(image!.path));
      _uploadToTencentCloud(res, image!);
      debugPrint('腾讯云上传地址: $res');
    });

    // 3. 上传文件到腾讯云
    // await _uploadToTencentCloud(uploadUrl, File(image!.path));
  } catch (e) {
    debugPrint('图片处理出错：${e.toString()}');
  }
}

//获取上传图片链接
Future<String> _getUploadUrl(String type) async {
  int timestampInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
  try {
    final response = await http.netFetch<GetUploadKeyModel>(
      CommonApi.getUploadKey,
      method: Method.post,
      params: {'key': '$timestampInSeconds.png','contentType': _getMimeType(type)},
    );

    if (response?.code == 200) {
      GlobalController controller = Get.find();
      controller.headImg.value = '${response?.data?.cdn}/${response?.data?.key}';
      // debugPrint('渠道图片地址: ${controller.avatarImg.value}');
      return '${response?.data?.uploadUrl}';
    }
    return '${response?.data?.uploadUrl}';
  } catch (e) {
    debugPrint('获取上传地址出错: ${e.toString()}');
    rethrow; // 重新抛出异常，让外层处理
  }
}

//图片颜色校正、压缩
Future<Uint8List> correctColor(XFile file) async {
  final image = img.decodeImage(await file.readAsBytes());
  final resized = img.copyResize(image!, width: 1024); // 限制最大宽度

  return img.encodePng(resized);
}

//上传图片
Future<bool> _uploadToTencentCloud(String url, XFile file) async {
  try {
    // final fileBytes = await file.readAsBytes();
    final fileBytes = await correctColor(file);

    // 创建独立的Dio实例，避免全局配置污染
    final dio = Dio(
      BaseOptions(
        responseType: ResponseType.plain, // 明确接收文本响应
        validateStatus: (status) => true, // 处理所有状态码
      ),
    );

    final response = await dio
        .put<String>(
          // 指定返回类型为String
          url,
          data: fileBytes,
          options: Options(
            headers: {
              'Content-Type': _getMimeType(file.name),
              // 'Content-Length': fileBytes.length.toString(),
            },
          ),
        )
        .then((res) {
          //  debugPrint('上传响应原始数据222: ${res}========');
          updateAvatarImg('$res');
        });

    // debugPrint('上传响应原始数据: ${response}========');

    // 根据状态码判断成功，而不是响应体内容
    if (response == null) {
      // 更新用户信息
      // globalController.getUserInfo();
      return true;
    }

    // 处理其他状态码
    throw DioException(
      requestOptions: response.requestOptions,
      response: response,
      error: '上传失败，状态码：${response.statusCode}',
    );
  } on DioException catch (e) {
    // 统一错误处理
    debugPrint('上传错误详情: ${e.message}');
    if (e.response != null) {
      debugPrint('错误响应头: ${e.response?.headers}');
      debugPrint('错误响应体: ${e.response?.data}');
    }
    showToast('上传失败: ${e.message ?? "未知错误"}');
    return false;
  }
}

String _getMimeType(String filename) {
  final ext = filename.split('.').last.toLowerCase();
  switch (ext) {
    case 'png':
      return 'image/png';
    case 'jpg':
      return 'image/jpeg';
    case 'jpeg':
      return 'image/jpeg';
    case 'gif':
      return 'image/gif';
    case 'webp':
      return 'image/webp';
    default:
      return 'application/octet-stream'; // 更通用的二进制类型
  }
}

void updateNickName(String nickName) async {
  if (nickName.isEmpty) {
    showToast('昵称不能为空');
    return;
  } else if (nickName.length > 15) {
    showToast('昵称不能超过15个字符');
    return;
  } else if (!RegExp(r'^[a-zA-Z0-9\u4e00-\u9fa5]+$').hasMatch(nickName)) {
    showToast('昵称只能包含数字、字母和文字');
    return;
  }
  http.netFetch<dynamic>(
    ApiUrl.updateUserInfo,
    method: Method.post,
    params: {'nickName': nickName},
    success: (r) {
      showToast('昵称已修改');
      GlobalController globalController = Get.find();
      globalController.getUserInfo();
    },
  );
}

void updateAvatarImg(String url) async {
  GlobalController controller = Get.find();

  http.netFetch<dynamic>(
    ApiUrl.updateUserInfo,
    method: Method.post,
    params: {'avatarImg': controller.headImg.value},
    success: (r) {
      // getUserInfo();
      GlobalController globalController = Get.find();
      globalController.getUserInfo();
    },
  );
}

Future<void> clearAppCache() async {
  final tempDir = await getTemporaryDirectory();
  final cacheDir = await getApplicationDocumentsDirectory();

  // 删除临时目录中的所有文件
  await deleteDirectoryContents(tempDir);

  // 删除应用文档目录中的缓存文件（假设缓存文件存储在'cache'子目录中）
  final cacheSubDir = Directory('${cacheDir.path}/cache');
  if (await cacheSubDir.exists()) {
    await deleteDirectoryContents(cacheSubDir);
  }
  showToast('清除成功');
}

Future<void> deleteDirectoryContents(Directory dir) async {
  if (await dir.exists()) {
    await for (final fileSystemEntity in dir.list()) {
      if (fileSystemEntity is File) {
        await fileSystemEntity.delete();
      } else if (fileSystemEntity is Directory) {
        await deleteDirectoryContents(fileSystemEntity);
        await fileSystemEntity.delete();
      }
    }
  }
}

void _logout() {
  http.netFetch(
    ApiUrl.logout,
    success: (data) {
      showToast('退出成功！');
      HiCache.getInstance().remove(LoginController.boardingPassToken);
      Get.offAllNamed(LoginPage.path);
    },
  );
}
